<template>
  <div class="login-view">
    <div class="head-container">
      <img src="/img/logo.png" alt="logo"/>
      <p>{{ WebTitle }}</p>
    </div>
    <div class="content-container">
      <div class="login-card">
        <p class="title">登录</p>
        <a-form :model="loginInfo">
          <a-form-item label="账号" name="account"
                       :rules="[{ required: true, message: '账号不能为空，请输入正确的账号！' },]">
            <a-input class="input" allowClear size="large" v-model:value="loginInfo.account"
                     placeholder="输入登录账号">
              <template #prefix>
                <UserOutlined/>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item label="密码" name="password" :rules="[{ required: true, message: '密码不能为空，请输入密码!' }]">
            <a-input-password class="input" allowClear size="large" v-model:value="loginInfo.password"
                              placeholder="输入登录密码">
              <template #prefix>
                <KeyOutlined/>
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item label="验证" name="identifyMode"
                       :rules="[{ required: true, message: '登录之前请输入右侧验证码进行验证' }]">
            <div class="verification-container">
              <a-input class="input" v-model:value="loginInfo.identifyMode" placeholder="输入验证码"></a-input>
              <div class="right" @click="refreshCode">
                <!-- 使用验证码组件 -->
                <Verification :identifyCode="identifyCode"></Verification>
              </div>
            </div>
          </a-form-item>

          <a-form-item>
            <div class="login-button-container">
              <a-button size="large" type="primary" @click="goHome" :icon="h(DesktopOutlined)" :loading="butLoading">
                登录
              </a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {h, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {DesktopOutlined, UserOutlined, KeyOutlined,} from "@ant-design/icons-vue";
import {message} from 'ant-design-vue';
import {setLoginInfo, setToken} from "@/utils/auth.ts";
import Verification from "../../components/Verification/index.vue";
import {WebTitle} from "../../../public/static/setting.ts";
import {loginRequest} from "@/api/basicsApi/systemManage/UserManage.ts";
import {initUserRoleMenu} from "@/utils/RouterUtil.ts";
import {useUserInfoStore} from "@/store/userInfo.ts";
import {getMenuTree} from "@/api/basicsApi/systemManage/MenuManage.ts";
import {MenuOperationInfo, MenuTreeRes} from "@/interface/basicsInterface/systemManage";
import {byKeyGetPath} from "@/utils/page/PageInfo.ts";
import {byAllPageGetKey} from "@/utils/page/PageInfo.ts";

const router = useRouter();

interface LoginState {
  account: string;
  password: string;
  identifyMode: string;
}

const loginInfo = ref<LoginState>({
  account: "",
  password: "",
  identifyMode: "",//输入框验证码
});
const butLoading = ref<boolean>(false);
let identifyCode = ref(""); //图形验证码
let identifyCodes = ref("1234567890"); //验证码出现的数字
const userStore = useUserInfoStore()
const allMenuTreeList = ref<MenuTreeRes[]>([])// 管控组件下的所有菜单

//组件挂载
onMounted(async () => {
  makeCode(identifyCodes.value, 4);
  const {data} = await getMenuTree()
  allMenuTreeList.value = data.children[1].children // 管控组件下的所有菜单
});

function goHome() {
  //验证验证码不为空
  if (!loginInfo.value.identifyMode) {
    message.error('验证码不能为空！');
    return
  }
  //验证验证码是否正确
  if (loginInfo.value.identifyMode != identifyCode.value) {
    message.error('验证码错误');
    loginInfo.value.identifyMode = ""
    refreshCode()
    return
  }

  butLoading.value = true;
  loginRequest(loginInfo.value.account, loginInfo.value.password).then(async (res: any) => {
    butLoading.value = false;
    message.success(res.msg);
    setToken(res.data.token)
    setLoginInfo(JSON.stringify(res.data))
    const data: MenuOperationInfo[] = await userStore.getRoleMenuRelFun(res.data.roles[0].roleId)
    const newPageList = initUserRoleMenu(data, allMenuTreeList.value)
    if (newPageList.length !== 0) {
      await router.replace({
        path: byKeyGetPath(byAllPageGetKey(newPageList), newPageList)
      });
    } else {
      await router.replace({
        path: "/emptyPage"
      })
    }
  }).catch(() => {
    butLoading.value = false;
    loginInfo.value.account = ""
    loginInfo.value.password = ""
    loginInfo.value.identifyMode = ""
    refreshCode()
  })
}

// 生成随机数
const randomNum = (min: number, max: number) => {
  max = max + 1;
  return Math.floor(Math.random() * (max - min) + min);
};

// 随机生成验证码字符串
function makeCode(o: any, l: any) {
  identifyCode.value = "";
  let code = "";
  do {
    code = "";
    for (let i = 0; i < l; i++) {
      code += o[randomNum(0, o.length)];
    }
  } while (code.includes("undefined"));
  identifyCode.value = code;
}

// 更新验证码
function refreshCode() {
  makeCode(identifyCodes.value, 4);
}
</script>

<style lang="scss" scoped>
@use "LoginView";
</style>
